"""
数据存储管理模块
"""
import json
import os
import time
from typing import Dict, List, Optional
import logging
from config import MONITOR_CONFIG, create_directories

logger = logging.getLogger(__name__)

class DataManager:
    def __init__(self):
        create_directories()
        self.authors_file = MONITOR_CONFIG["authors_file"]
        self.history_file = MONITOR_CONFIG["history_file"]

        # 初始化数据文件
        self._init_files()

    def _init_files(self):
        """初始化数据文件"""
        # 初始化作者数据文件
        if not os.path.exists(self.authors_file):
            with open(self.authors_file, 'w', encoding='utf-8') as f:
                json.dump({}, f, ensure_ascii=False, indent=2)

        # 初始化历史记录文件
        if not os.path.exists(self.history_file):
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump([], f, ensure_ascii=False, indent=2)

    def load_authors(self) -> Dict:
        """加载作者数据"""
        try:
            with open(self.authors_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"加载作者数据失败: {str(e)}")
            return {}

    def save_authors(self, authors_data: Dict):
        """保存作者数据"""
        try:
            with open(self.authors_file, 'w', encoding='utf-8') as f:
                json.dump(authors_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存作者数据失败: {str(e)}")

    def load_history(self) -> List[Dict]:
        """加载历史记录"""
        try:
            with open(self.history_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"加载历史记录失败: {str(e)}")
            return []

    def save_history(self, history_data: List[Dict]):
        """保存历史记录"""
        try:
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(history_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存历史记录失败: {str(e)}")

    def update_author_data(self, author_id: int, new_data: Dict) -> Dict:
        """
        更新作者数据，返回变化信息
        """
        authors = self.load_authors()
        author_key = str(author_id)

        # 获取旧数据
        old_data = authors.get(author_key, {})

        # 保存新数据
        authors[author_key] = {
            **new_data,
            "last_update": time.time()
        }
        self.save_authors(authors)

        # 计算变化
        changes = self._calculate_changes(old_data, new_data)

        # 如果有变化，记录到历史
        if changes:
            self._add_to_history(author_id, changes)

        return changes

    def _calculate_changes(self, old_data: Dict, new_data: Dict) -> Dict:
        """计算数据变化"""
        changes = {
            "timestamp": time.time(),
            "author_id": new_data.get("author_id"),
            "username": new_data.get("username", ""),
            "changes": {}
        }

        # 比较粉丝数
        old_followers = old_data.get("follower_count", 0)
        new_followers = new_data.get("follower_count", 0)
        if old_followers != new_followers:
            changes["changes"]["followers"] = {
                "old": old_followers,
                "new": new_followers,
                "diff": new_followers - old_followers
            }

        # 比较作品数据
        old_illusts = {illust["illust_id"]: illust for illust in old_data.get("illusts", [])}
        new_illusts = {illust["illust_id"]: illust for illust in new_data.get("illusts", [])}

        # 检查新作品
        new_works = []
        for illust_id, illust in new_illusts.items():
            if illust_id not in old_illusts:
                new_works.append(illust)

        if new_works:
            changes["changes"]["new_illusts"] = new_works

        # 检查作品数据变化
        updated_illusts = []
        for illust_id, new_illust in new_illusts.items():
            if illust_id in old_illusts:
                old_illust = old_illusts[illust_id]
                diff = {}

                if old_illust.get("like_count") != new_illust.get("like_count"):
                    diff["likes"] = {
                        "old": old_illust.get("like_count", 0),
                        "new": new_illust.get("like_count", 0),
                        "diff": new_illust.get("like_count", 0) - old_illust.get("like_count", 0)
                    }

                if old_illust.get("bookmark_count") != new_illust.get("bookmark_count"):
                    diff["bookmarks"] = {
                        "old": old_illust.get("bookmark_count", 0),
                        "new": new_illust.get("bookmark_count", 0),
                        "diff": new_illust.get("bookmark_count", 0) - old_illust.get("bookmark_count", 0)
                    }

                if diff:
                    updated_illust.append({
                        "illust_id": illust_id,
                        "title": new_illust.get("title", ""),
                        "changes": diff
                    })

        if updated_illusts:
            changes["changes"]["updated_illusts"] = updated_illusts

        return changes if changes["changes"] else {}

    def _add_to_history(self, author_id: int, changes: Dict):
        """添加变化记录到历史"""
        history = self.load_history()
        history.append(changes)

        # 限制历史记录数量，保留最近1000条
        if len(history) > 1000:
            history = history[-1000:]

        self.save_history(history)

    def get_author_latest_data(self, author_id: int) -> Optional[Dict]:
        """获取作者最新数据"""
        authors = self.load_authors()
        return authors.get(str(author_id))

    def get_recent_changes(self, author_id: Optional[int] = None, limit: int = 50) -> List[Dict]:
        """获取最近的变化记录"""
        history = self.load_history()

        # 过滤特定作者
        if author_id:
            history = [record for record in history if record.get("author_id") == author_id]

        # 按时间倒序排列，返回最新的记录
        history.sort(key=lambda x: x.get("timestamp", 0), reverse=True)
        return history[:limit]

    def get_monitored_authors(self) -> List[int]:
        """获取正在监控的作者ID列表"""
        authors = self.load_authors()
        return [int(author_id) for author_id in authors.keys()]

    def remove_author(self, author_id: int):
        """移除作者监控"""
        authors = self.load_authors()
        author_key = str(author_id)

        if author_key in authors:
            del authors[author_key]
            self.save_authors(authors)
            logger.info(f"已移除作者{author_id}的监控")
            return True
        return False

    def cleanup_old_history(self, days: int = 30):
        """清理旧的历史记录"""
        history = self.load_history()
        cutoff_time = time.time() - (days * 24 * 3600)

        filtered_history = [record for record in history
                          if record.get("timestamp", 0) > cutoff_time]

        self.save_history(filtered_history)
        logger.info(f"已清理{days}天前的历史记录")